package cs4280.ass2.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import cs4280.ass2.entity.Member;
import cs4280.ass2.entity.User;
import cs4280.ass2.exception.ValidateException;
import cs4280.ass2.persistence.MemberDao;

public class MemberAreaAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		HttpSession session = req.getSession();
		User user = (User) session.getAttribute("loggedInUser");
		if (user.getId() < 0) { //
			resp.sendRedirect("index.jsp");
		} else {
			Member member = MemberDao.getInstance().retrieveMember(user.getId());
			req.setAttribute("member", member);
			getServletContext().getRequestDispatcher("/member_area.jsp").forward(req, resp);
		}
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		HttpSession session = req.getSession();
		User user = (User) session.getAttribute("loggedInUser");
		String changePassword = req.getParameter("changePassword");
		if (StringUtils.equals(changePassword, "1")){
			String oldPassword = StringUtils.trim(req.getParameter("oldPassword"));
			String newPassword = StringUtils.trim(req.getParameter("newPassword"));
			String newPassword2 = StringUtils.trim(req.getParameter("newPassword2"));
			
			if (StringUtils.equals(newPassword, newPassword2))
				try {
					throw new ValidateException("message.error.validate.changePassword.new-new2");
				} catch (ValidateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			boolean isMatch = MemberDao.getInstance().matchPassword(user.getId(), oldPassword);
			if (isMatch){
				MemberDao.getInstance().changePassword(user.getId(), newPassword);
			}
			req.setAttribute("message.info", "message.info.movie.changepasswordsuccess");
			resp.sendRedirect("/member.do");
		}
		
	}
}
